import BiosafetyAPI from '../../../common/api/ctn/auditmain.api.js';
import doT from '../../../../vendor/template/doT.js';
import { DictionaryType, requestDict } from "../../../common/dictionary/dictionary-type.js";
import { uploadFile, requestFilePath, publicFileDraw, sliceFileName } from "../../../common/api/file-request.js";

(function (window, document, $) {
    let _vm, _auditTypeData, listindex = "", _isQualifiedEntry = {}, _addressData = [], _resultOptions = [];
    const detailsTemplate = doT.template($('#details-template').text());
    const _json = Utils.ParsingUrl(window.location);
    $(function () {
        $('body').attr('data-weui-theme', 'light'); //强制光明模式
        _initCommand();
        liststatues();
        _ctlReturn();
        doRectify();
    });

    //命令初始化
    const _initCommand = async () => {
        //审查地点查询
        _addressData = await requestDict(DictionaryType.AUDITADDRESS_TYPE);
        //整改情况
        _resultOptions = await requestDict(DictionaryType.RESULT_TYPE);
        //初始化类型
        requestDict(DictionaryType.AUDIT_TYPE).then(res => {
            _auditTypeData = res.data;
            _queryDetails();
        });
        //返回列表
        $(document).on('click', '#submitItemTab', function () {
            location.href = `../prodsafetymgt/auditmain.html?v=${Utils.GetTime()}&type=${_json.type}`;
        });
    }

    // 导航栏切换
    const liststatues = () => {
        $('#spleplan-navbar a').on('click', function () {
            let track = false;
            let falseEntry = [];
            listindex = Number($(this).index());
            $(this).addClass('weui-bar__item--on').siblings().removeClass('weui-bar__item--on');
            if (listindex == 0) {
                track = false, falseEntry = [];
                falseEntry = _isQualifiedEntry.entries.filter(s => s.isQualified == false);
                if (falseEntry.length == 0) {
                    return $('#detailsEntry').empty().append('<div style="text-align: center;padding: 120px;">暂无不合格项内容~</div>')
                }
            } else {
                track = true, falseEntry = [];
                falseEntry = _isQualifiedEntry.entries.filter(s => s.isQualified == true);
                if (falseEntry.length == 0) {
                    return $('#detailsEntry').empty().append('<div style="text-align: center;padding: 120px;">暂无合格项内容~</div>')
                }
            }
            let entry = falseEntry.map(item => {
                let _result = [];
                item.entries.forEach(s => {
                    let slt = { result: _resultOptions.data.find(itm => itm.value == s.result)?.displayName, trackImage: s.trackImage, trackRemark: s.trackRemark, trackTime: s.trackTime };
                    _result.push(slt);
                });
                return {
                    ...item,
                    _result
                }
            })
            _viewImages(entry);
            $('#detailsEntry').empty().append(detailsTemplate({ 'array': entry, 'track': track, 'remark': _isQualifiedEntry.remark }));
        })
    }

    // 控制返回按钮，返回的页面
    const _ctlReturn = () => {
        if (window.history && window.history.pushState) {
            history.pushState(null, null, document.URL);
            window.addEventListener('popstate', function () {
                history.pushState(null, null, document.URL);
                //跳转列表
                this.window.location = `../prodsafetymgt/auditmain.html?v=${Utils.GetTime()}&type=${_json.type}`;
            });
        }
    }

    //详情查询
    const _queryDetails = () => {
        BiosafetyAPI.getAuditFormBills(_json.id).then(res => {
            $('#company').val(res.company?.name||'')
            $('#department').val(res.department?.name||'')
            $('#scoreDate').val(moment(res.scoreDate).format('YYYY-MM-DD'))
            $('#scorer').val(res.scorer)
            $('#adress').val(res.adressName)

            _isQualifiedEntry = res;
            let falseEntry = res.entries.filter(s => s.isQualified == false);
            if (falseEntry.length == 0) {
                return $('#detailsEntry').empty().append('<div style="text-align: center;padding: 120px;">暂无不合格项内容~</div>')
            }

            let entry = falseEntry.map(item => {
                let _result = [];
                item.entries.forEach(s => {
                    let slt = { result: _resultOptions.data.find(itm => itm.value == s.result)?.displayName, trackImage: s.trackImage, trackRemark: s.trackRemark, trackTime: s.trackTime };
                    _result.push(slt);
                });
                return {
                    ...item,
                    _result
                }
            })
            $('#detailsEntry').empty().append(detailsTemplate({ 'array': entry, 'track': false, 'remark': res.remark,  }));
            _viewImages(entry);
        })
    }

    //附件循环赋值
    const _imageshow = async (id, image, num) => {
        let _sun = 0;
        let _list = image.split(',');
        for (let i = 0; i < _list.length; i++) {
            await requestFilePath(_list[i]).then(res => {
                if (res.isSucceed) {
                    let _li = `<li class="weui-uploader__file${num} weui-attachment" data-id="${_sun}" data-url="${res.data}"  style="background-image: url(${res.data}) "></li>`;
                    $(`#${id}${num}`).append(_li);
                }
            });
        }
    }
    const _entriesImageshow = async (id, image, num, seq) => {
        let _sun = 0;
        let _list = image.split(',');
        for (let i = 0; i < _list.length; i++) {
            await requestFilePath(_list[i]).then(res => {
                if (res.isSucceed) {
                    let _li = `<li class="weui-uploader__file${seq} weui-entries-attachment" data-id="${_sun}" data-url="${res.data}"  style="background-image: url(${res.data}) "></li>`;
                    $(`#${id}${seq}`).append(_li);
                }
            });
        }
    }

    //附件循环回显
    const _viewImages = (imagesEntry) => {
        $.each(imagesEntry, function (i, v) {
            if (Utils.IsNotNull(v.image)) {
                _imageshow('uploaderFiles', v.image, i + 1);
                _imagesMessage('uploaderFiles', i + 1);
            }
            $.each(v.entries, function (j, x) {
                if (Utils.IsNotNull(x.trackImage)) {
                    _entriesImageshow('trackImage', x.trackImage, i + 1, j + 1 + 1 + i);
                    _imagesMessage('trackImage', j + 1 + 1 + i);
                }
            })
        })
    }

    //放大附件查看
    const _imagesMessage = (id, number) => {
        $(document).on('click', `#${id}${number}`, function (e) {
            let target = e.target;
            while (!target.classList.contains(`weui-uploader__file${number}`) && target) {
                target = target.parentNode;
            }
            if (!target) return;
            //从图片对应的li标签中获得所需属性
            let gallery = weui.gallery($(target).attr('data-url'), {
                className: 'custom-name',
            });
            $('.weui-icon_gallery-delete').css('display', 'none')
        });
    }
    // 点击提交整改
    const doRectify = () => {
        $(document).on('click', `[btn-type="rectify"]`, function () {
            let auditFormBillId = $(this).data('auditformbillid')
            let seq = $(this).data('seq')
            location.href = `../prodsafetymgt/rectifyaudit.html?auditFormBillId=${auditFormBillId}&seq=${seq}&type=${_json.type}`
        })
    }


})(window, document, jQuery)